package com.adhere.security.feign;

import com.adhere.common.constants.SecurityConstants;
import com.adhere.common.utils.IpUtils;
import com.adhere.common.utils.ObjectUtils;
import com.adhere.common.utils.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 使用 feign 进行请求的时候将 设置的请求头传递下去
 *
 * @author WT
 * @date 2022/02/11 11:14:25
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        HttpServletRequest httpServletRequest = ServletUtils.getRequest();

        if (httpServletRequest != null) {

            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            // 传递用户信息请求头，防止丢失
            String userId = headers.get(SecurityConstants.USER_ID);
            if (ObjectUtils.isNotEmpty(userId)) {
                requestTemplate.header(SecurityConstants.USER_ID, userId);
            }
            String userName = headers.get(SecurityConstants.LOGIN_NAME);
            if (ObjectUtils.isNotEmpty(userName)) {
                requestTemplate.header(SecurityConstants.LOGIN_NAME, userName);
            }
            String authentication = headers.get(SecurityConstants.TOKEN_AUTHORIZATION);
            if (ObjectUtils.isNotEmpty(authentication)) {
                requestTemplate.header(SecurityConstants.TOKEN_AUTHORIZATION, authentication);
            }

            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddress(ServletUtils.getRequest()));

        }
    }
}